//
//  UIDevice(Identifier).m
//  UIDeviceAddition
//

#import "UIDevice+Identifier_Addition.h"
#import "NSString+MD5Addition.h"
#import <sys/utsname.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import <AdSupport/AdSupport.h>
#import <mach/mach_host.h>
#import <dlfcn.h>
#import "LHELLIOKitDumper.h"
#import "LHHUtil.h"
#import "GTMBase64.h"
#import "GTMDefines.h"
#include <objc/runtime.h>

@interface UIDevice(Private)

- (NSString *) macaddress;

@end

@implementation UIDevice (IdentifierAddition)

////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private Methods

// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.


- (NSString *) macaddress
{
    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        free(buf);
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return outstring;
}

////////////////////////////////////////////////////////////////////////////////
#pragma mark - Public Methods
- (NSString *) uniqueDeviceIdentifierr
{
    NSString *osversion = [[UIDevice currentDevice] systemVersion];
    if( [osversion compare:@"7.0"] >= NSOrderedSame  ){
        NSString *ads = [self getIdfaRuntime];
        NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
        NSString *stringToHash = [NSString stringWithFormat:@"%@%@",ads,bundleIdentifier];
        NSString *identifier = [stringToHash stringFromMD5];
       
        
        return identifier;
    }else{
        NSString *macaddress = [[UIDevice currentDevice] macaddress];
        
        NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
        NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier];
        NSString *identifier = [stringToHash stringFromMD5];
        
        return identifier;
    }
}

- (NSString *) uniqueDeviceIdentifierrWithoutMd5
{
    NSString *osversion = [[UIDevice currentDevice] systemVersion];
    if( [osversion compare:@"7.0"] >= NSOrderedSame ){
        return [self getIdfaRuntime];
    }else{
        NSString *macaddress = [[UIDevice currentDevice] macaddress];
        macaddress = [macaddress stringByReplacingOccurrencesOfString:@":" withString:@""];
        return macaddress;
    }
}

- (NSString *) uniqueGlobalDeviceIdentifierr
{
    NSString *osversion = [[UIDevice currentDevice] systemVersion];
    if( [osversion compare:@"7.0"] >= NSOrderedSame ){
        NSString *ads = [self getIdfaRuntime];
       // DDLogWarn(@"%@",ads);
        NSString *identifier = [ads stringFromMD5];
        return identifier;
    }else{
        NSString *macaddress = [[UIDevice currentDevice] macaddress];
        NSString *identifier = [macaddress stringFromMD5];
        return identifier;
    }
}


- (NSString *)getBatteryID
{
    NSString *osversion = [[UIDevice currentDevice] systemVersion];
    if( [osversion compare:@"7.0"] >= NSOrderedSame ){
        NSString *batteryID = [LHELLIOKitDumper searchIOProperty:@"battery-id"];
        NSString *identifier = @"";
        NSData *data = [[LHHUtil sharedLHHUtil] EncodeTEA:batteryID];
       // DDLogDebug(@"%@",data);
        identifier = [GTMBase64 stringByEncodingData:data];
        return identifier;
    }else{
        NSString *macaddress = [[UIDevice currentDevice] macaddress];
        NSData *data = [[LHHUtil sharedLHHUtil] EncodeTEA:macaddress];
        NSString* identifier = [GTMBase64 stringByEncodingData:data];
        return identifier;
    }
}

- (NSString *)getDeviceInfo
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *deviceMachine = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    sysctlbyname("hw.model", NULL, &size, NULL, 0);
    char *model = malloc(size);
    sysctlbyname("hw.model", model, &size, NULL, 0);
    NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
    free(model);
    
    struct utsname unameInfo;
    uname(&unameInfo);
    NSString *unameNodename = [NSString stringWithCString:unameInfo.nodename encoding:NSUTF8StringEncoding];
    NSString *unameVersion = [NSString stringWithCString:unameInfo.version encoding:NSUTF8StringEncoding];
    NSString *unameMachine = [NSString stringWithCString:unameInfo.machine encoding:NSUTF8StringEncoding];
    
    UIDevice *device = [UIDevice currentDevice];
    
    NSString *deviceString = [NSString stringWithFormat:@"%@, %@|%@, %@, %@, %@|%@, %@, %@", deviceMachine, deviceModel, [device name], [device systemName], [device systemVersion], [device model], unameNodename, unameVersion, unameMachine];
    
    return deviceString;
}

- (NSString *)getDeviceMachine
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *deviceMachine = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    return deviceMachine;
}

static void *libAdSupport = NULL;

- (NSString *)getIdfaRuntime
{
    char path[256];
    sprintf(path, "%s%s%s%s%s%s%s%s%s", "/Sys", "tem/L", "ibrar", "y/Framewo", "rks/A", "dSuppor", "t.fram", "ework/Ad", "Support");
    NSString *idfa = nil;
        Class ASIdentifierManager_class = NSClassFromString(@"ASIdentifierManager");
        if (ASIdentifierManager_class) {
            ASIdentifierManager *asiManager = [ASIdentifierManager_class performSelector:@selector(sharedManager)];
            NSUUID *uuid = [asiManager performSelector:@selector(advertisingIdentifier)];
            idfa = [uuid performSelector:@selector(UUIDString)];
        } else {
            libAdSupport = dlopen(path, RTLD_LAZY);
            ASIdentifierManager_class = NSClassFromString(@"ASIdentifierManager");
            if (ASIdentifierManager_class) {
                ASIdentifierManager *asiManager = [ASIdentifierManager_class performSelector:@selector(sharedManager)];
                NSUUID *uuid = [asiManager performSelector:@selector(advertisingIdentifier)];
                idfa = [uuid performSelector:@selector(UUIDString)];
            }
        }
    return idfa;
}
@end
